from exts import db
from datetime import datetime


class StarListModel(db.Model):
    __tablename__ = "star_list"
    # 用户open_id
    star_user_id = db.Column(db.String(32), db.ForeignKey('user.open_id'), primary_key=True)
    # 博客id
    star_blog_id = db.Column(db.Integer, db.ForeignKey('blog.blog_id'), primary_key=True)
    # 收藏创建时间
    create_date = db.Column(db.DateTime, nullable=False, default=datetime.now)

    # 关系
    user = db.relationship('UserModel', back_populates='starlists')
    blog = db.relationship('BlogModel', back_populates='starlists')

    def to_dict(self):
        return {c.name: self._convert_value(getattr(self, c.name, None)) for c in self.__table__.columns}

    @staticmethod
    def _convert_value(value):
        if isinstance(value, datetime):
            return int(value.timestamp() * 1000)  # 转换为毫秒级时间戳
        return value
